var geocoder;
var map;
var records;
var cityStrings = [];
var cityStrings1=[];
var counter =0;
/*
 * prepares the locations to query Google map
 */
function getRecords() {
	var repeatation=0;
	var counter=0;
	var canvas = document.getElementById('mapDetail')
	if(!canvas){
		records = document.getElementsByClassName("cell");
 
   		for (var i=0; i < records.length; i++) {
 	   		for (var j=0; j < counter+1; j++) {
 	 	  		if(cityStrings[j]== records[i].innerHTML){ 	 			
 	 	  			repeatation=1;
 	 			}
 	    	}
 	   		if(repeatation===0){
 		  		cityStrings[counter] = records[i].innerHTML;
 		    	counter=counter+1;
 	    	}
 	    	repeatation=0;
 		};
 		initialize();
	}
	else{
		var town = document.getElementById('Town')
		cityStrings[0]=town.innerHTML
		initialize();

	}
}

function initialize() {
   	geocoder = new google.maps.Geocoder();
   	var latlng = new google.maps.LatLng(46.0, 9.0);
   	var myOptions = {
       	zoom :8,
       	center : latlng,
       	mapTypeId : google.maps.MapTypeId.ROADMAP
   	}
 	if(document.getElementById('mapDetail')){
 		document.getElementById("map_canvas").style.display = 'none';
 		map = new google.maps.Map(document.getElementById("mapDetail"), myOptions);
 		time();
 		return counter
 	}
   	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
   	time();
}
/*
 * google map api for encoding location names 
 */
var namecity;
function codeAddress() {
	element = cityStrings;
	namecity= cityStrings[counter];
	var j=0
    geocoder.geocode({'address' : "switzerland,"+cityStrings[counter]}, function(results, status) {
    	if(status == google.maps.GeocoderStatus.OK) {
          	map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
             	map : map,
                position : results[0].geometry.location
            });
           	j = j + 1;
            marker.setTitle(j.toString());
            attachSecretMessage(marker, j,namecity);
     	} else {
              
       	}
 	}); 



}
/*
 * timer controlling the number of requests for marker sent 
 */
function time(){
	
 	var timer=setInterval(function(){
 		codeAddress();
 		if(counter===cityStrings.length){
 			clearInterval();
 		}
 		counter=counter+1;	
 	},800);
	
 }
/*
 * to put the image and some data on the map object when a marker is clicked
 */
var info=[];
function attachSecretMessage(marker, number,namecity) {
	if(imgs){
		var message = ["<html><body><p><table><tr><td><img src="+linkImage+" width=70px height=100px/></td></p><td><p>"+document.getElementById("Kanton").textContent+", "+namecity+
					"<br>"+document.getElementById("Biulding").textContent+"</p></td></tr></table> </body></html>", "my USI"];
	}
	else {
		var message = ["<html><body><h2>"+namecity+"</h2></body></html>"];
	};
	var infowindow = new google.maps.InfoWindow({
		content : message[0],
		size : new google.maps.Size(25, 25)
	});
	google.maps.event.addListener(marker, 'click', function() {
		closeInfos();
		info[0]=infowindow;
		infowindow.open(map, marker);
	});
	
}
function closeInfos(){
  if(info.length > 0){
     /* detach the info-window from the marker */
     info[0].set("marker",null);
     /* and close it */
     info[0].close();
     /* blank the array */
     info.length = 0;
  }
}
/*
 * This method is called when the body loads and the search results table is loaded 
 * It's purpose is to call functions based on some conditions 
 */
var linkImage;
var imgs;
function lookUp(){
	getStates()
	if(document.getElementById('mapDetail')){
		getRecords()
	}
	if (document.getElementById('searchResults')) {
		if (document.getElementById('town').textContent === "" || document.getElementById('code').textContent === "") {
			getRecords()
		}
	} else if (document.getElementById('organLocation')){
		//var url = "/image/"
		var url ="http://www.orgeldokumentationszentrum.ch/de/classes/image.php"
		var building = document.getElementById('id');
		var output = document.getElementById('image');					

		if (building) {
			linkImage=url+ "?id="+building.textContent;
			var reqState = new XMLHttpRequest(); 
			reqState.open("GET", "/image?id="+building.textContent, true );
			reqState.onreadystatechange = function() {
				if (reqState.readyState == 3) { 
					//output.innerHTML = "loading..."
				}; 
				if (reqState.readyState == 4) {
					var image = reqState.responseText
					linkImage=url+ "?id="+building.textContent;
					imgs = '<img src= '+url+ "?id="+building.textContent+' width= "150px" height ="200px">'
					if (!imgs) {
						output.style.display=none
					}
					else{
						output.innerHTML = imgs;
					}
					
				}
			}
			reqState.send(null);	
			
		} 	
	}
}
/*
 * populates the drop down box with the list of kantons in switzerland
 */
function getStates(){
	var url = "/kanton"
	var output = document.getElementById('mymenu')
	var xmlhttp = new XMLHttpRequest(); 
	xmlhttp.open("GET", url, true );
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 3) { 
		}; 
		if (xmlhttp.readyState == 4) {
			output.innerHTML=xmlhttp.responseText;
		};
	}
	xmlhttp.send(null);	 
};